Lumen & Gesso / website · lumengesso.com / app / api / orders / [id] / checkout / route.ts
| 1 | import { NextResponse, type NextRequest } from 'next/server'; |
| 2 | import { physicalCheckoutEnabled, physicalCheckoutPausedMessage } from '@/app/lib/free-studio-checkout'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { stripe } from '@/app/lib/stripe'; |
| 5 | import { env } from '@/app/lib/env'; |
| 6 | import { displayOrderId } from '@/app/lib/orders'; |
| 7 | import { SHIPPING_COUNTRIES } from '@/app/lib/shipping'; |
| 8 | |
| 9 | // POST /api/orders/[id]/checkout |
| 10 | // ------------------------------------------------------------------ |
| 11 | // Creates a Stripe Checkout Session for the customer's commission AT |
| 12 | // SUBMIT TIME (not at design-approval time). The Builder's "Continue to |
| 13 | // payment" button routes the customer to /checkout, /checkout calls |
| 14 | // /api/orders to create the order row, then calls this endpoint to mint |
| 15 | // the Stripe session, then redirects to the Stripe-hosted page. |
| 16 | // |
| 17 | // On successful Stripe payment, the webhook (app/api/webhooks/stripe) |
| 18 | // transitions the order from pending_payment → pending_design and |
| 19 | // sends the magic-link email so the customer can track their order. |
| 20 | // |
| 21 | // This is intentionally NOT auth-gated (the customer hasn't completed |
| 22 | // magic-link login yet at submit time); it relies on Stripe's metadata |
| 23 | // orderId for downstream linking. Anyone with an orderId could trigger |
| 24 | // session creation, but they'd just be paying for someone else's |
| 25 | // commission — non-harmful. |
| 26 | |
| 27 | export const runtime = 'nodejs'; |
| 28 | export const dynamic = 'force-dynamic'; |
| 29 | |
| 30 | export async function POST( |
| 31 | req: NextRequest, |
| 32 | ctx: { params: Promise<{ id: string }> }, |
| 33 | ) { |
| 34 | if (!physicalCheckoutEnabled()) { |
| 35 | return NextResponse.json({ error: physicalCheckoutPausedMessage, studio: '/studio' }, { |
| 36 | status: 503, |
| 37 | headers: { 'Cache-Control': 'no-store' }, |
| 38 | }); |
| 39 | } |
| 40 | |
| 41 | const { id } = await ctx.params; |
| 42 | |
| 43 | // termsAccepted is the customer's explicit consent to the refund |
| 44 | // policy shown on /checkout. Required to mint a Stripe session — we |
| 45 | // also persist the timestamp on the order row for auditability. |
| 46 | let body: { email?: string; termsAccepted?: boolean }; |
| 47 | try { |
| 48 | body = await req.json(); |
| 49 | } catch { |
| 50 | return NextResponse.json({ error: 'invalid json' }, { status: 400 }); |
| 51 | } |
| 52 | if (body.termsAccepted !== true) { |
| 53 | return NextResponse.json( |
| 54 | { error: 'You must accept the refund policy and terms to continue.' }, |
| 55 | { status: 400 }, |
| 56 | ); |
| 57 | } |
| 58 | |
| 59 | const admin = commerceDb(); |
| 60 | const { data: order, error: fetchErr } = await admin |
| 61 | .from('orders') |
| 62 | .select('id, user_email, status, price_cents, config, stripe_session_id') |
| 63 | .eq('id', id) |
| 64 | .single(); |
| 65 | |
| 66 | if (fetchErr || !order) { |
| 67 | return NextResponse.json({ error: 'order not found' }, { status: 404 }); |
| 68 | } |
| 69 | if ( |
| 70 | order.status !== 'pending_payment' |
| 71 | && order.status !== 'pending_design' |
| 72 | && order.status !== 'abandoned' |
| 73 | ) { |
| 74 | // pending_design is allowed for backwards-compat (legacy flow). |
| 75 | // abandoned is allowed for the resume-payment flow: customer |
| 76 | // returns to a stale order via /checkout?orderId=…&canceled=1 |
| 77 | // and re-pays. We transition them back to pending_payment so |
| 78 | // the Stripe webhook handler (which only matches pending_payment) |
| 79 | // can move them forward normally. |
| 80 | return NextResponse.json( |
| 81 | { error: `cannot start checkout from status ${order.status}` }, |
| 82 | { status: 409 }, |
| 83 | ); |
| 84 | } |
| 85 | if (order.status === 'abandoned') { |
| 86 | await admin.from('orders').update({ status: 'pending_payment' }).eq('id', id); |
| 87 | } |
| 88 | |
| 89 | // Record terms acceptance before creating the Stripe session. |
| 90 | await admin.from('orders').update({ |
| 91 | terms_accepted_at: new Date().toISOString(), |
| 92 | }).eq('id', id); |
| 93 | |
| 94 | const cfg = (order.config ?? {}) as { productId?: string; size?: string; styleId?: string }; |
| 95 | |
| 96 | const session = await stripe().checkout.sessions.create({ |
| 97 | mode: 'payment', |
| 98 | payment_method_types: ['card'], |
| 99 | line_items: [{ |
| 100 | price_data: { |
| 101 | currency: 'usd', |
| 102 | unit_amount: order.price_cents, |
| 103 | // tax_behavior is REQUIRED when automatic_tax is enabled. |
| 104 | // 'exclusive' = our advertised price is pre-tax; Stripe Tax |
| 105 | // computes FL state + county surtax (and any other registered |
| 106 | // jurisdiction) and adds it on top at checkout. |
| 107 | tax_behavior: 'exclusive', |
| 108 | product_data: { |
| 109 | name: `Lumen & Gesso commission · ${displayOrderId(order.id)}`, |
| 110 | description: `${cfg.styleId ?? 'custom'} · ${cfg.productId ?? ''} ${cfg.size ?? ''}`.trim(), |
| 111 | // Generic tangible goods tax category. Stripe's default works |
| 112 | // for framed art / canvas — taxable in jurisdictions that |
| 113 | // tax tangible personal property. Override only if FL or |
| 114 | // another jurisdiction ever flags this as the wrong category. |
| 115 | tax_code: 'txcd_99999999', |
| 116 | }, |
| 117 | }, |
| 118 | quantity: 1, |
| 119 | }], |
| 120 | customer_email: order.user_email, |
| 121 | // Stripe's type expects a mutable AllowedCountry[]; SHIPPING_COUNTRIES |
| 122 | // is `as const` so we shallow-copy to satisfy the assignment. |
| 123 | shipping_address_collection: { allowed_countries: [...SHIPPING_COUNTRIES] }, |
| 124 | // Stripe Tax: computes the right rate per delivery address. Uses |
| 125 | // the shipping address Stripe collects above (or the billing |
| 126 | // address on the card) and applies whichever registered |
| 127 | // jurisdiction matches. Returns zero tax for addresses in |
| 128 | // jurisdictions where we have no registration. |
| 129 | // |
| 130 | // Note: `customer_update` is intentionally omitted — it requires a |
| 131 | // pre-existing `customer` parameter, which we don't have on a |
| 132 | // first-time guest checkout (we only have `customer_email`). |
| 133 | // automatic_tax still works fine with just the shipping address |
| 134 | // the customer enters at checkout. |
| 135 | automatic_tax: { enabled: true }, |
| 136 | metadata: { orderId: order.id }, |
| 137 | payment_intent_data: { |
| 138 | metadata: { orderId: order.id }, |
| 139 | // NOTE: intentionally NO receipt_email. Stripe's auto-receipt is |
| 140 | // account-level ("Receipt from Protomota, LLC", shared with Jotley). |
| 141 | // We send our own fully Lumen & Gesso-branded receipt from the |
| 142 | // checkout.session.completed webhook instead (receiptHtml). |
| 143 | }, |
| 144 | success_url: `${env.site.url()}/login/check-email?orderId=${order.id}&email=${encodeURIComponent(order.user_email)}&paid=1`, |
| 145 | cancel_url: `${env.site.url()}/checkout?orderId=${order.id}&canceled=1`, |
| 146 | }); |
| 147 | |
| 148 | await admin.from('orders').update({ stripe_session_id: session.id }).eq('id', id); |
| 149 | |
| 150 | if (!session.url) return NextResponse.json({ error: 'no checkout url' }, { status: 500 }); |
| 151 | return NextResponse.json({ url: session.url }); |
| 152 | } |